<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import CustomFormItem from '@/components/basic/CustomFormItem.vue'
import RefundAccountTypeFormItem from '@/components/basic/RefundAccountTypeFormItem.vue'
import { queryOrderRefundInfo, queryOrderDetailInfo } from '@/api/order'
import { submitCmRefundApply, resubmitDepositRefund } from '@/api/expense'
import {
  OrderInfoType,
  queryOrderRefundInfoResponseData,
  queryOrderDetailInfoResponseData
} from '@/api/order/types/order'
import { validateMoney } from '@/utils/formvalidate'
import { getToken } from '@/utils/cache/cookies'
import { OptionsType, AliPayRefundData, BankRefundData } from '@/types/interface'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { defineAsyncComponent } from 'vue'

const dialogVisible = ref<boolean>(false)
const title = ref<string>('押金退款申请')
const open = () => {
  dialogVisible.value = true
}
const setData = (
  phone: string,
  orderId: string,
  orderType: string,
  id: number,
  applyAmount: number
) => {
  form.phone = phone
  form.orderId = orderId
  type.value = orderType
  userId.value = id
  form.applyAmount = applyAmount
  disabled.value = true
  isResubmit.value = true
  getOrderInfo()
}
defineExpose({ open, setData })
const form = reactive({
  phone: '',
  orderId: '',
  applyAmount: 0,
  accountType: '原路退回',
  applyReason: ''
})
const formRef = ref<FormInstance | null>(null)
const rules = reactive<FormRules>({
  phone: [{ required: true, message: '请输入用户手机号', trigger: 'blur' }],
  orderId: [{ required: true, message: '请选择订单号', trigger: 'change' }],
  applyAmount: [
    {
      required: true,
      validator: validateMoney,
      trigger: 'blur'
    }
  ],
  accountType: [{ required: true, message: '请选择退款渠道', trigger: 'change' }],
  applyReason: [{ required: true, message: '请输入退款原因', trigger: 'blur' }]
})
/** 根据用户手机号获取退款信息 */
const data = ref<(queryOrderRefundInfoResponseData & Record<string, any>) | null>(null)
const refundType = ref<OptionsType[]>([])
const batteryOrder = ref<OrderInfoType[] | undefined>([])
const bikeOrder = ref<OrderInfoType[] | undefined>([])
const OrderList = ref<OrderInfoType[]>([])
const getUserRefundInfo = async () => {
  try {
    if (!form.phone) return

    selectLoading.value = true
    const res = await queryOrderRefundInfo({
      token: getToken() ?? '',
      phone: form.phone,
      type: 'partial',
      orderId: form.orderId
    })
    if (res.statusCode === '0') {
      data.value = res.data
      refundType.value = res.data.refundType
      batteryOrder.value = res.data.batteryOrder
      bikeOrder.value = res.data.bikeOrder
      userId.value = res.data.userId
    }
    selectLoading.value = false
  } catch (error) {
    console.error(error)
    selectLoading.value = false
  }
}
/** 根据选择的订单 查询订单信息  */
const orderData = ref<queryOrderDetailInfoResponseData | null>(null)
const getOrderInfo = async () => {
  try {
    loading.value = true
    const res = await queryOrderDetailInfo({
      userId: userId.value.toString(),
      token: getToken() ?? '',
      orderId: form.orderId
    })
    if (res.statusCode === '0') {
      orderData.value = res.data
      form.applyAmount = canRefundDepositForAmount.value
    }
    loading.value = false
  } catch (error) {
    console.error(error)
    loading.value = false
  }
}
const type = ref<string>('')
const userId = ref<number>(0)
/** 根据选择的订单的表单加载状态 */
const loading = ref<boolean>(false)
/** 下拉选择加载状态 */
const selectLoading = ref<boolean>(false)
/** 重新提交 禁用 */
const disabled = ref<boolean>(false)
const isResubmit = ref<boolean>(false)
/** 切换退款类型时 切换订单号选项 */
const handleChangeType = () => {
  OrderList.value = data.value![type.value]
}
/** 选择退款渠道时 支付宝数据或者银行卡数据 */
const AliAccountData = reactive<AliPayRefundData & Record<string, any>>({
  aliName: '',
  aliAccount: ''
})
const BankAccountData = reactive<BankRefundData & Record<string, any>>({
  bankName: '',
  bankBranchName: '',
  username: '',
  card: ''
})
/** 计算可退押金 */
const canRefundDepositForAmount = computed(() => {
  const deposit = orderData.value?.orderRefundData.canRefundDeposit
  if (deposit?.includes('（')) {
    const index = deposit.indexOf('（')
    const str = deposit.slice(0, index - 1)
    return str.includes('元') ? +str.split('元')[0] : +str
  } else {
    return +(deposit ?? '0')
  }
})
/** 当取消弹框时 */
const handleClose = () => {
  formRef.value?.resetFields()
  data.value = null
  refundType.value = []
  batteryOrder.value = []
  bikeOrder.value = []
  orderData.value = null
  userId.value = 0
  type.value = ''
  OrderList.value = []
  disabled.value = false
  isResubmit.value = false
  for (const key in AliAccountData) {
    if (Object.prototype.hasOwnProperty.call(AliAccountData, key)) {
      AliAccountData[key] = ''
    }
  }
  for (const key in BankAccountData) {
    if (Object.prototype.hasOwnProperty.call(BankAccountData, key)) {
      BankAccountData[key] = ''
    }
  }
}
/** 是否传入accountData */
const AccountData = computed(() => {
  if (form.accountType === '原路退回') return
  if (form.accountType === '支付宝') {
    return AliAccountData
  } else {
    return BankAccountData
  }
})
/** 打开支付宝权限dialog */
const AliPayPermissionDialog = defineAsyncComponent(
  () => import('@/components/dialog/AliPayPermission.vue')
)
const AliPayPermissionDialogRef = ref<InstanceType<typeof AliPayPermissionDialog> | null>(null)
const handleOpen = () => {
  AliPayPermissionDialogRef.value?.open()
}
/**
 * @description 提交表单
 * @todo 待验证
 */
const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      isResubmit.value ? resubmitRequest() : submitRequest()
    }
  })
}
const submitRequest = () => {
  submitCmRefundApply({
    token: getToken() ?? '',
    applyType: 'DEPOSIT_REFUND',
    ...form,
    type: '',
    accountData: AccountData.value
  })
    .then((res) => {
      if (res.statusCode === '0') {
        ElMessage.success(res.data)
        dialogVisible.value = false
      }
    })
    .catch((error) => {
      console.error(error)
    })
}
const resubmitRequest = () => {
  resubmitDepositRefund({
    orderId: form.orderId,
    accountData: AccountData.value,
    token: getToken() ?? ''
  })
    .then((res) => {
      if (res.statusCode === '0') {
        ElMessage.success(res.data)
        dialogVisible.value = false
      }
    })
    .catch((error) => {
      console.error(error)
    })
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="650px"
    class="deposit-refund-application-dialog"
    @close="handleClose"
  >
    <el-form :model="form" label-width="120px" ref="formRef" :rules="rules" v-loading="loading">
      <el-form-item prop="phone" label="用户手机号:">
        <el-input v-model="form.phone" @change="getUserRefundInfo" :disabled="disabled" />
      </el-form-item>
      <el-form-item prop="type" label="退款类型:">
        <el-select
          v-model="type"
          @change="handleChangeType"
          :loading="selectLoading"
          remote
          :remote-method="getUserRefundInfo"
          :disabled="disabled"
        >
          <el-option
            v-for="({ label, value }, index) in refundType"
            :key="index"
            :label="label"
            :value="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="orderId" label="订单:">
        <el-select v-model="form.orderId" @change="getOrderInfo" :disabled="disabled">
          <el-option
            v-for="({ orderId, name }, index) in OrderList"
            :key="index"
            :label="orderId + '(' + name + ')'"
            :value="orderId"
          />
        </el-select>
      </el-form-item>
      <Transition mode="out-in">
        <div v-if="orderData">
          <custom-form-item>
            <template #label>
              <span>订单状态:</span>
            </template>
            <template #value>
              <span>{{ orderData.bizData.orderDetailStatusDescription }}</span>
            </template>
            <template #label2>
              <span>押金金额:</span>
            </template>
            <template #value2>
              <span>{{ orderData.productSnapshot.deposit }}元</span>
            </template>
          </custom-form-item>
          <custom-form-item :first-col="24" :last-col="0">
            <template #label>
              <span>可退押金:</span>
            </template>
            <template #value>
              <span class="text-warning-light">{{
                orderData.orderRefundData.canRefundDeposit
              }}</span>
            </template>
          </custom-form-item>
          <el-form-item prop="applyAmount" label="退款金额:">
            <el-input v-model="form.applyAmount" type="number" :disabled="disabled">
              <template #prepend>￥</template>
            </el-input>
          </el-form-item>
          <el-form-item prop="applyReason" label="退款原因">
            <el-input
              v-model="form.applyReason"
              type="textarea"
              :min="2"
              placeholder="请输入退款原因"
            />
          </el-form-item>
          <refund-account-type-form-item
            -ali-value="支付宝"
            -bank-value="银行卡"
            -origin-value="原路退回"
            v-model="form"
            v-model:alipay="AliAccountData"
            v-model:bank="BankAccountData"
            :apartTime="orderData?.orderRefundData.apartTime ?? true"
            @open="handleOpen"
          />
        </div>
      </Transition>
    </el-form>
    <template #footer>
      <el-button plain @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
  <ali-pay-permission-dialog ref="AliPayPermissionDialogRef" />
</template>

<style scoped></style>
